/**
 * <pre>
 * Title: 		DailyIterator.java
 * Project: 	AnteAgent
 * Type:		com.hengpeng.anteagent.scheduling.iterators.DailyIterator
 * Author:		linriqing
 * Create:	 	2007-1-16 10:12:53
 * Copyright: 	Copyright (c) 2007
 * Company:		
 * <pre>
 */
package com.hengpeng.common.scheduling.iterators;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.tiling.scheduling.ScheduleIterator;

/**
 * <pre>
 * 按天循环的迭代器
 * </pre>
 * @author linriqing
 * @version 1.0, 2007-1-16
 */
public class DailyIterator implements ScheduleIterator
{
	private int interval;

	private final Calendar calendar;

	private final List<Date> dateList;

	private int iterIndex;

	private static final Log logger = LogFactory.getLog(ComplexWeeklyIterator.class);

	private final Calendar tempdate;

	/**
	 * 构造函数
	 * @param interval 迭代的天数
	 * @param timeStrings 时间字符串数组, 例如: new String[] {"08:00:00", "09:00:00", "18:00:00" }
	 */
	public DailyIterator(int interval, String[] timeStrings)
	{
		this.interval = interval;

		calendar = Calendar.getInstance();
		tempdate = Calendar.getInstance();
		tempdate.set(Calendar.YEAR, 1970);
		tempdate.set(Calendar.MONTH, Calendar.JANUARY);
		tempdate.set(Calendar.DATE, 1);

		dateList = new ArrayList<Date>();

		// 主要是兼容类似10:7:00方式的时间参数
		for (int i = 0; i < timeStrings.length; i++)
		{
			try
			{
				String timeStr = timeStrings[i];
				DateFormat df = new SimpleDateFormat("HH:mm:ss");
				Date date = df.parse(timeStr);
				if (!dateList.contains(date))
				{
					dateList.add(date);
				}
			}
			catch (ParseException e)
			{
				logger.error("时间格式错误", e);
				continue;
			}
		}

		Collections.sort(dateList);
		iterIndex = dateList.size();
		for (int i = 0; i < dateList.size(); i++)
		{
			Date date = (Date) dateList.get(i);
			if (date.after(tempdate.getTime()))
			{
				iterIndex = i;
				break;
			}
		}
	}

	public Date next()
	{
		if (iterIndex >= dateList.size())
		{
			iterIndex = 0;
			calendar.add(Calendar.DATE, this.interval);

		}
		tempdate.setTime((Date) dateList.get(iterIndex));
		iterIndex++;

		tempdate.set(Calendar.YEAR, calendar.get(Calendar.YEAR));
		tempdate.set(Calendar.MONTH, calendar.get(Calendar.MONTH));
		tempdate.set(Calendar.DATE, calendar.get(Calendar.DATE));

		return tempdate.getTime();
	}
}
